import React, { Component } from 'react';
import { connect } from 'dva';
import {
  Button, Steps, Popover, Badge, Table, Tooltip, Divider, Modal, Form, message,
  List, Card, Row, Col, Radio, Input, Progress, Icon, Dropdown, Menu, Avatar
} from 'antd';
import numeral from 'numeral';
import DemoComponent from '../../components/Demo';
import NumberInfo from '../../components/NumberInfo';
import { getTimeDistance } from '../../utils/utils';
import { getAuthority, setAuthority } from '../../utils/authority';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';

import styles from './UserCenter.less';

const FormItem = Form.Item;
@Form.create()
@connect(state => ({
  userState: state.user,
  systemUserState: state.systemUser
}))
export default class UserCenter extends Component {
  state = {
    confirmDirty: false,
    editedEntity: {},
    passwordModalVisible: false,
    mobileModalVisible: false,
  };

  componentWillMount() {
  }

  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'user/fetchCurrent',
    });

  }

  onMobileEditClick = () => {
    this.setState({
      mobileModalVisible: true,
    });

  }

  onPasswordEditClick = () => {
    this.setState({
      passwordModalVisible: true,
    });
  }

  handlePasswordModalSubmit = () => {
    const { dispatch, form } = this.props;
    form.validateFields(['password', 'passwordSure'], (err, fieldsValue) => {
      if (err) return;

      if(this.props.userState.currentUser && this.props.userState.currentUser.userId) {
        this.props.userState.currentUser.id = this.props.userState.currentUser.userId
        delete this.props.userState.currentUser.userId
      }

      if(this.props.userState.currentUser && this.props.userState.currentUser.userName) {
        this.props.userState.currentUser.name = this.props.userState.currentUser.userName
        delete this.props.userState.currentUser.userName
      }
      
      dispatch({
        type: 'systemUser/changePassword',
        payload: {
          ...this.props.userState.currentUser,
          password: fieldsValue.password,
        },
        callback: (code, msg) => {
          if (code == 200) {
            message.success(`${msg}，请重新登陆`);
            this.setState({ passwordModalVisible: false });
            form.resetFields();
            dispatch({
              type: 'user/fetchCurrent',
            });
          } else {
            message.error(msg);
          }
        },
      });
    });
  }

  handleConfirmBlur = (e) => {
    const value = e.target.value;
    this.setState({ confirmDirty: this.state.confirmDirty || !!value });
  }

  checkPassword = (rule, value, callback) => {
    const form = this.props.form;
    if (value && value !== form.getFieldValue('password')) {
      callback('两次输入的密码不相同');
    } else {
      callback();
    }
  }

  checkConfirm = (rule, value, callback) => {
    const form = this.props.form;
    if (value && this.state.confirmDirty) {
      form.validateFields(['passwordSure'], { force: true });
    }
    callback();
  }

  handleMobileModalSubmit = () => {
    const { dispatch, form } = this.props;
    form.validateFields(['mobile'], (err, fieldsValue) => {
      if (err) return;

      if(this.props.userState.currentUser && this.props.userState.currentUser.userId) {
        this.props.userState.currentUser.id = this.props.userState.currentUser.userId
        delete this.props.userState.currentUser.userId
      }

      if(this.props.userState.currentUser && this.props.userState.currentUser.userName) {
        this.props.userState.currentUser.name = this.props.userState.currentUser.userName
        delete this.props.userState.currentUser.userName
      }

      dispatch({
        type: 'systemUser/edit',
        payload: {
          ...this.props.userState.currentUser,
          mobile: fieldsValue.mobile,
        },
        callback: (code, msg) => {
          if (code == 200) {
            message.success(`${msg}`);
            this.setState({ mobileModalVisible: false });
            form.resetFields();
            dispatch({
              type: 'user/fetchCurrent',
            });

          } else {
            message.error(msg);
          }
        },
      });
    });

  }

  checkMobile = (rule, value, callback) => {
    const form = this.props.form;
    if (value && value.length != 11) {
      callback('手机号格式有误');
    } else {
      callback();
    }
  }

  render() {

    const { userState, systemUserState, form } = this.props;
    const { getFieldDecorator } = form;

    const wrapperLabelCol = {
      xs: { span: 24 },
      sm: { span: 24 },
      md: { span: 24 },
      lg: { span: 6 },
    };

    const wrapperContentCol = {
      xs: { span: 24 },
      sm: { span: 24 },
      md: { span: 24 },
      lg: { span: 15 },
    };

    const wrapperOperCol = {
      xs: { span: 24 },
      sm: { span: 24 },
      md: { span: 24 },
      lg: { span: 3 },
    };

    const wrapperFormCol = {
      xs: { span: 24 },
      sm: { span: 24 },
      md: { span: 24 },
    };


    return (
      <PageHeaderLayout
        title="个人中心"
      >

        <Card
          bordered={false}
          // bodyStyle={{ padding: '16px 128px 40px 128px' }}
          className={styles.standardCard}
        >
          <List
            size="large"
            rowKey="id"
          // loading={loading}
          >
            <List.Item >
              <Row>
                <Col {...wrapperLabelCol}><span>帐户名</span></Col>
                <Col {...wrapperContentCol}><span>{userState.currentUser.userName}</span></Col>
                <Col {...wrapperOperCol}></Col>
              </Row>
              <Row>
                <Col {...wrapperLabelCol}><span>绑定手机号</span></Col>
                <Col {...wrapperContentCol}><span>{userState.currentUser.mobile}</span></Col>
                <Col {...wrapperOperCol}>
                  <a onClick={() => this.onMobileEditClick()}>
                    变更
                  </a>
                </Col>
              </Row>
              <Row>
                <Col {...wrapperLabelCol}><span>登陆密码</span></Col>
                <Col {...wrapperContentCol}><span>登陆商家平台时需要输入密码</span></Col>
                <Col {...wrapperOperCol}>
                  <a onClick={() => this.onPasswordEditClick()}>
                    重置
                  </a>
                </Col>
              </Row>
              <Row>
                <Col {...wrapperLabelCol}><span>账户角色</span></Col>
                <Col {...wrapperContentCol}>
                  <span>
                    {userState.currentUser.primaryRole ? userState.currentUser.primaryRole.roleName : (userState.currentUser.roleName ? userState.currentUser.roleName : '')}
                    {/* 开发人员<Divider type="vertical" />
                    开发人员<Divider type="vertical" />
                    开发人员<Divider type="vertical" />
                    开发人员 */}
                  </span>
                </Col>
                <Col {...wrapperOperCol}></Col>
              </Row>
              <Row>
                <Col {...wrapperLabelCol}><span>账户类型</span></Col>
                <Col {...wrapperContentCol}>
                  <span>
                    {/* 主账户 */}
                  </span>
                </Col>
                <Col {...wrapperOperCol}></Col>
              </Row>
              <Row>
                <Col {...wrapperLabelCol}><span>姓名</span></Col>
                <Col {...wrapperContentCol}><span>
                  {userState.currentUser.loginName}
                </span></Col>
                <Col {...wrapperOperCol}></Col>
              </Row>
              <Row>
                <Col {...wrapperLabelCol}><span>隶属企业</span></Col>
                <Col {...wrapperContentCol}>
                  <span>
                    {userState.currentUser.organization ? userState.currentUser.organization.organizationName : ''}
                  </span>
                </Col>
                <Col {...wrapperOperCol}></Col>
              </Row>
            </List.Item>


          </List>
        </Card>

        <Modal className={styles.modalForm}
          title="修改密码"
          visible={this.state.passwordModalVisible}
          onCancel={() => { this.setState({ passwordModalVisible: false }); }}
          onOk={() => this.handlePasswordModalSubmit()}
          width={800}
        >
          <Form layout="inline">
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
              <Col {...wrapperFormCol}   >
                <FormItem label="密码">
                  {getFieldDecorator("password", {
                    rules: [{
                      required: true, message: '请输入密码',
                    }, {
                      validator: this.checkConfirm,
                    }],
                  })(<Input placeholder="请输入密码" type="password" />)
                  }
                </FormItem>
                <FormItem label="确认密码">
                  {getFieldDecorator("passwordSure", {
                    rules: [{
                      required: true, message: '请确认密码',
                    }, {
                      validator: this.checkPassword,
                    }],
                  })(<Input placeholder="请确认密码" type="password" onBlur={this.handleConfirmBlur} />)
                  }
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Modal>

        <Modal className={styles.modalForm}
          title="修改手机号"
          visible={this.state.mobileModalVisible}
          onCancel={() => { this.setState({ mobileModalVisible: false }); }}
          onOk={() => this.handleMobileModalSubmit()}
          width={800}
        >
          <Form layout="inline">
            <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
              <Col {...wrapperFormCol}   >
                <FormItem label="手机号">
                  {getFieldDecorator("mobile", {
                    rules: [{
                      required: true, message: '请输入手机号',
                    }, {
                      validator: this.checkMobile,
                    }],
                  })(<Input placeholder="请输入手机号" />)
                  }
                </FormItem>
              </Col>
            </Row>
          </Form>
        </Modal>


      </PageHeaderLayout>



    );
  }
}
